<?php
/**
 * Author: Vuong Huynh Hoai Huong (hoaihuong@9webdesigns.com)
 * 
 * @category   default 
 * @copyright  Copyright (c) 2009 visualidea.org
 * @license    http://license.visualidea.org
 * @version    v 1.0 2009-04-15
 * 
 */
require_once 'modules/bkcard/models/BKCard.php';
require_once 'modules/bkcard/models/BKCardCategory.php';
class bkcard_AdminController extends Nine_Controller_Action_Admin 
{
    
    public function newCardAction()
    {
        /**
         * Check permission
         */
        if (false == $this->checkPermission('new_bkcard')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        $objBKCard = new Models_BKCard();
        $objCategory = new Models_BKCardCategory();
        $data = $this->_getParam('data', false);
        
        $errors = array();
        if (false != $data) {
       		try {
       			if (null != @$data['number_of']) {
       				
       				$newBKCard = $data;
		            unset($newBKCard['value']);
		            unset($newBKCard['number_of']);
       				$newBKCard['created_date'] = time();
					if (null != @$newBKCard['expired_date']) {
						$tmp = explode("/", trim($newBKCard['expired_date']));
						$newBKCard['expired_date'] = mktime(0,0,0,@$tmp[1],@$tmp[0],@$tmp[2]);
					}
		            $newBKCard['purchased'] = 0;
		            
		            $cat = $objCategory->getCategoryById($data['bkcard_category_id']);
		            
       				for($i = 0; $i < $data['number_of']; $i++) {
		       		 	if (null != @$data['bkcard_category_id']) {
			            	/**
					         * Generate code and value for card type
					         */
			            	$code = $objBKCard->generateCode();
			            	$newBKCard['code'] = $cat['alias'] . $code;
			            }
			            /**
			             * Insert new bkcard
			             */
			            $objBKCard->insert($newBKCard);
       				}
		            
       			}
          		$this->session->bkcardMessage =  array(
		   						'success' => true,
		                       	'message' => Nine_Language::translate('BKCard is created successfully.')
                    		);
                $this->_redirect('bkcard/admin/manage-card');
                
           } catch (Exception $e) {
                $errors = array('main' => Nine_Language::translate('Can not insert into database now'));
           }
        }
        
      
        $code = $objBKCard->generateCode();
        $allCategories = $objCategory->getAllEnabledCategory(array(),array('name ASC'));
        
        /**
         * Prepare for template
         */
        $this->view->errors = $errors;
        $this->view->data = $data;
        $this->view->headTitle(Nine_Language::translate('New BKCard'));
        $this->view->menu = array('bkcard', 'newcard');
        $this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
        $this->view->allCategories = $allCategories;
    }
    

    public function editCardAction()
    {
        /**
         * Check permission
         */
        if (false == $this->checkPermission('edit_bkcard')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $id   = $this->_getParam('id', false);
        $data = $this->_getParam('data', false);
    
        if (false == $id) {
            $this->_redirect('bkcard/admin/manage-card');
        }
    
        $objBKCard = new Models_BKCard();
        $objCategory = new Models_BKCardCategory();
        $errors = array();
        
        /**
         * Get old bkcard
         */
        $oldBKCard = $objBKCard->getBKCardById($id);
        
        if (empty($oldBKCard)) {
            /**
             * BKCard doesn't exsit
             */
            
            $this->session->bkcardMessage = array(
                                           'success' => false,
                                           'message' => Nine_Language::translate('BKCard does NOT exist')
                                       );
            $this->_redirect('bkcard/admin/manage-card#listofbkcard');
        }
        
        if (false !== $data) {
            /**
             * Update new bkcard
             */
            $newBKCard = $data;
            unset($newBKCard['bkcard_category_id']);
            unset($newBKCard['code']);
            unset($newBKCard['value']);
            
        	if (null != @$newBKCard['expired_date']) {
				$tmp = explode("/", trim($newBKCard['expired_date']));
				$newBKCard['expired_date'] = mktime(0,0,0,@$tmp[1],@$tmp[0],@$tmp[2]);
			}
            try {
                $objBKCard->update ( $newBKCard, array ('bkcard_id=?' => $id ) );
                $this->session->bkcardMessage = array(
                                           'success' => true,
                                           'message' => Nine_Language::translate('BKCard is updated successfully')
                                   );
                $this->_redirect('bkcard/admin/manage-card');
                    
            } catch (Exception $e) {
				$errors = array('main' => Nine_Language::translate('Can not update bkcard now'));
				$this->session->bkcardMessage = array(
                                       'success' => false,
                                       'message' => Nine_Language::translate('Can not update bkcard now')
                                   );
                }
        } else {
            /**
             * Get current bkcard
             */
            $data = $oldBKCard;
            if (null != @$data['expired_date']){
            	$data['expired_date'] = date(Nine_Registry::getConfig('dateFormat'),$data['expired_date']);
            }
        }
        
        /**
         * Generate code and value for card type
         */
        $code = $objBKCard->generateCode();
        $allCategories = $objCategory->getAllEnabledCategory(array(),array('name ASC'));
//        foreach($allCategories as &$cat) {
//        	$cat['code'] = $cat['alias'] . $code;
//        }
//        unset($cat);
        
        /**
         * Prepare for template
         */
        $this->view->errors = $errors;
        $this->view->data = $data;
        $this->view->headTitle(Nine_Language::translate('Edit BKCard'));
        $this->view->menu = array('bkcard', 'editcard');
		$this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
		$this->view->allCategories = $allCategories;
    }
    
    public function manageCardAction()
    {
        /**
         * Check permission
         */
        if (false == $this->checkPermission('see_bkcard')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $this->view->headTitle(Nine_Language::translate('Manage BKCards'));
        $this->view->menu = array('bkcard', 'managecard');
        
        $config = Nine_Registry::getConfig();
        $numRowPerPage = Nine_Registry::getConfig("defaultNumberRowPerPage");
        $currentPage = $this->_getParam("page",1);
        $displayNum = $this->_getParam('displayNum', false);
        
        /**
         * Get number of bkcards per page
         */
        if (false === $displayNum) {
            $displayNum = $this->session->bkcardDisplayNum;
        } else {
            $this->session->bkcardDisplayNum = $displayNum;
        }
        if (null != $displayNum) {
            $numRowPerPage = $displayNum;
        }
        /**
         * Get condition
         */
        $condition = $this->_getParam('condition', false);
        if (false === $condition) {
            $condition = $this->session->bkcardCondition;
        } else {
            $this->session->bkcardCondition = $condition;
            $currentPage = 1;
        }
        if (false == $condition) {
            $condition = array();
        }
        /**
         * Load all bkcards
         */
        $objBKCard = new Models_BKCard();
        $allBKCards = $objBKCard->getAllBKCard($condition, 'bkcard_id DESC',
                                                   $numRowPerPage,
                                                   ($currentPage - 1) * $numRowPerPage
                                                  );
        /**
         * Count all bkcards
         */
        $count = count($objBKCard->getAllBKCard($condition));
        $this->view->condition = $condition;
        /**
         * Modify all bkcards
         */
        foreach ($allBKCards as &$bkcard) {
            if (null != $bkcard['created_date']) {
                $bkcard['created_date'] = date($config['dateFormat'], $bkcard['created_date']);
            }
            if (null != $bkcard['expired_date']) {
                $bkcard['expired_date'] = date($config['dateFormat'], $bkcard['expired_date']);
            }
            if (null != @$bkcard['value']) {
            	$bkcard['value_format'] = $objBKCard->makeUpNumber($bkcard['value']) . " " . $config['defaultCurrency'];
            }
        }
        unset($bkcard);
        /**
         * Set values for tempalte
         */
        $this->setPagination($numRowPerPage, $currentPage, $count);
        $this->view->allBKCards = $allBKCards;
        $this->view->bkcardMessage = $this->session->bkcardMessage;
        $this->session->bkcardMessage = null;
        $this->view->displayNum = $numRowPerPage;
    }
    
    public function enableCardAction()
    {
        /**
         * Check permission
         */
        if (false == $this->checkPermission('edit_bkcard')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        $id = $this->_getParam('id', false);
        
        if (false == $id) {
            $this->_redirect('bkcard/admin/manage-card');
        }
        
        $ids = explode('_', trim($id, '_'));
        
        $objBKCard = new Models_BKCard();
        try {
            foreach ($ids as $id) {
               $objBKCard->update(array('enabled' => 1), array('bkcard_id=?' => $id));
            }
            $this->session->bkcardMessage = array(
                                               'success' => true,
                                               'message' => Nine_Language::translate('BKCard is activated successfully')
                                           );
        } catch (Exception $e) {
            $this->session->bkcardMessage = array(
                                               'success' => false,
                                               'message' => Nine_Language::translate('Can NOT enable this bkcard. Please try again')
                                           );
        }
        $this->_redirect('bkcard/admin/manage-card#listofbkcard');
    }

    
    
    public function disableCardAction()
    {
        /**
         * Check permission
         */
        if (false == $this->checkPermission('edit_bkcard')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $id = $this->_getParam('id', false);
        
        if (false == $id) {
            $this->_redirect('bkcard/admin/manage-card');
        }
        
        $ids = explode('_', trim($id, '_'));
        
        $objBKCard = new Models_BKCard();
        try {
            foreach ($ids as $id) {
               $objBKCard->update(array('enabled' => 0), array('bkcard_id=?' => $id ));
            }
            $this->session->bkcardMessage = array(
                                               'success' => true,
                                               'message' => Nine_Language::translate('BKCard is deactived successfully')
                                           );
        } catch (Exception $e) {
            $this->session->bkcardMessage = array(
                                               'success' => false,
                                               'message' => Nine_Language::translate('Can NOT disable this bkcard. Please try again')
                                           );
        }
        $this->_redirect('bkcard/admin/manage-card#listofbkcard');
    }

    public function deleteCardAction()
    {
        /**
         * Check permission
         */
        if (false == $this->checkPermission('delete_bkcard')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $id = $this->_getParam('id', false);
        
        if (false == $id) {
            $this->_redirect('bkcard/admin/manage-card');
        }
        
        $ids = explode('_', trim($id, '_'));
        
        $objBKCard = new Models_BKCard();
        try {
            foreach ($ids as $id) {
               $objBKCard->delete( array('bkcard_id=?' => $id ));
            }
            $this->session->bkcardMessage = array(
                                               'success' => true,
                                               'message' => Nine_Language::translate('BKCard is deleted successfully')
                                           );
        } catch (Exception $e) {
            $this->session->bkcardMessage = array(
                                               'success' => false,
                                               'message' => Nine_Language::translate('Can NOT delete this bkcard. Please try again')
                                           );
        }
        $this->_redirect('bkcard/admin/manage-card#listofbkcard');
    }
}